--[[
从集合中挑选出超时未收到客户端响应需要重发的上行短信
--]]

local from =  tonumber(ARGV[1])
local to = tonumber(ARGV[2])
local count = tonumber(ARGV[3])
local array = {}
local index = 0

local list = redis.call("zrevrangebyscore", KEYS[1], to, from, "limit", 0, count)

for i,v in ipairs(list) do

    local result = redis.call("zrem", KEYS[2], v)

    if (result == 1) then
    	redis.call("zrem", KEYS[1], v)
        redis.call("del", "SMMoDealHash:"..v)
    else
    	local ntfhvalue = redis.call("hmget", "SMMoDealHash:"..v, "ISMCacheKey", "IRptSnPart1", "IRptSnPart2", "IRptSnPart3", "ISendTimes", "ILastSendTime")
	    local cacheKey = ntfhvalue[1]
	    if (cacheKey ~= nil and cacheKey ~= false) then
	    	index = index + 1
	        array[index] = ntfhvalue
	        redis.call("zrem", KEYS[1], v)
	        redis.call("del", "SMMoDealHash:"..v)
	        if (index >= count) then 
	            break
	        end
	    end
    end
end

return array